//
//  testViewController.m
//  DYChats
//
//  Created by 杨德勇 on 2016/9/12.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

#import "testViewController.h"
#import <GCDAsyncUdpSocket.h>
@interface testViewController ()<GCDAsyncUdpSocketDelegate>

@end

@implementation testViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blueColor];
    [self openUDPServer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)openUDPServer{
    dispatch_queue_t dqueue = dispatch_queue_create("test", nil);
    //初始化udp
    GCDAsyncUdpSocket *tempSocket=[[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dqueue socketQueue:nil];
    self.udpSocket=tempSocket;
    
    //绑定端口
    NSError *error = nil;
    [self.udpSocket bindToPort:4444 error:&error];
//    [self.udpSocket joinMulticastGroup:@"224.0.0.1" error:&error];
    
    //启动接收线程
    
//    [self.udpSocket beginReceiving:&error];
    NSLog(@"ydy - %@",error);
//    [self.udpSocket receiveWithTimeout:-1 tag:0];
    
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"ydy - 点击了屏幕");
    [self sendMessage:@"我发了一次消息"];
}

//连接建好后处理相应send Events
-(void)sendMessage:(NSString*)message
{
    NSMutableString *sendString = [NSMutableString stringWithCapacity:100];
    [sendString appendString:message];
    //开始发送
    [self.udpSocket sendData:[sendString dataUsingEncoding:NSUTF8StringEncoding]
                                 toHost:@"224.0.0.1"
                                   port:4333
                            withTimeout:-1
                                    tag:0];
    
    
   }


-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
   
    NSString *ip = [GCDAsyncUdpSocket hostFromAddress:address];
    uint16_t port = [GCDAsyncUdpSocket portFromAddress:address];
    NSString *msg = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"ydy - 收2到来自：%@:%d 的消息:%@",ip,port,msg);
    
}
-(void)dealloc{
    NSLog(@"%s",__func__ );
    [self.udpSocket close];
    self.udpSocket = nil;
}

@end
